var api = require("../../api.js"),
  qqmapsdk,
  QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js'),
  app = getApp();
const {
  $Toast
} = require('../../iview/base/index');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    proData: {},
    isHavedCollect: 0,
    /** 图片高度 */
    img_height: 0,
    show: false,
    phone: '',
    name: '',
    /** 省份 */
    province: '',
    /** 城市 */
    city: '',
    /** 区域 */
    district: '',
    /** 地址 */
    address: null,
    /** 详细地址 */
    detail: '',
    /** 按钮加载状态 */
    loading: false,
    /** 按钮是否禁用状态 */
    disabled: false,
    user_address: [],
    /** 地址实体 */
    address_obj: null,
    /** 选择的地址id */
    address_id: '',
    address_show: false,
  },
  /**
   * 生命周期函数--监听页面加载
   *
   */
  onLoad: function (options) {
    console.log('options.id', options.id)
    this.setData({
      id: options.id,
      window_w: wx.getSystemInfoSync().windowWidth,
    })
    /** 这里写你自己的秘钥 */
    qqmapsdk = new QQMapWX({
      /** 自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请 */
      key: 'EH4BZ-VL3C3-EKL3H-YQCOD-YPOFS-ORB6J'
    });
    if(options.address_id != undefined){
      this.address_obj(options.address_id)
      this.setData({
        address_id: options.address_id
      })
    }else{
      this.default_address()
    }
  },
  /** 获取用户默认地址 */
  default_address() {
    const _this = this;
    const param = {
      open_id: app.globalData.wxUserInfo.openId
    };
    app.request.requestGetApi(api.user.default_address, param, this,
      function (res) {
        if (res.data != null) {
          console.log('获取用户默认地址数据返回 --> ', res)
          _this.setData({
            address_obj: res.data,
            address_id: res.data.id,
          })
        }
      })
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  /** 选择地址 */
  sel_address() {
    this.setData({
      address_show: true
    })
    /** 获取用户地址列表 */
    this.user_address()
  },
  /** 获取用户地址列表 */
  user_address() {
    const _this = this
    app.request.requestGetApi(api.user.user_address, {
        open_id: app.globalData.wxUserInfo.openId
      }, this,
      function (res) {
        _this.setData({
          user_address: res.data
        })
      })
  },
  /** 确认选择地址 */
  confirm_address(e) {
    var a_id = e.currentTarget.id
    this.address_obj(a_id);
    this.setData({
      address_id: a_id,
      address_show: false
    })
  },
   /** 根据 id 获取地址 */
   address_obj(id) {
    const _this = this;
    app.request.requestGetApi(api.user.address_obj, {
        id: id
      }, this,
      function (res) {
        _this.setData({
          address_obj: res.data
        })
      })
  },

  /** 立即购买 */
  buy_product() {
    console.log(this.data.proData.title)
    var _this = this;
    if (_this.data.address_id.length != 0) {
      _this.setData({
        loading: true,
        disabled: true
      })
      /** 传输的数据 */
      let param = {
        openId: app.globalData.wxUserInfo.openId,
        /** 商品id */
        otherId: _this.data.id,
        /** 社群id */
        communityId: _this.data.proData.product.comm_id,
        money: _this.data.proData.product.presentPrice,
        paymentMoney: _this.data.proData.product.presentPrice,
        /** 购买的商品名称 */
        body: _this.data.proData.product.title,
        type: 2,
        addressId: _this.data.address_id
      }
      wx.request({
        url: api.active.tobuy,
        data: param,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success(res) {
          console.log('完成支付 res -->> ', res)
          if (res.data.code == 200) {
            /** 支付返回 */
            wx.requestPayment({
              timeStamp: res.data.data.timeStamp,
              nonceStr: res.data.data.nonceStr,
              package: res.data.data.package,
              signType: res.data.data.signType,
              paySign: res.data.data.paySign,
              success(res) {
                console.log("支付成功");
              },
              fail(res) {
                $Toast({
                  content: '支付失败',
                  icon: 'delete'
                });
              },
              /** 方法完成事件 */
              complete(res) {
                setTimeout(() => {
                  _this.setData({
                    loading: false,
                    disabled: false
                  })
                }, 1000);
                /** 支付成功 */
                if (res.errMsg == "requestPayment:ok") {
                  /** 延迟1s 提示 */
                  setTimeout(() => {
                    $Toast({
                      content: '支付成功',
                      type: 'success'
                    });
                  }, 500);
                  wx.redirectTo({
                    url: '/pages/community/community?communitiesId=' + _this.data.proData.product.comm_id,
                  })
                } else {
                  /** 未支付成功 res.errMsg == "request:ok" */
                  $Toast({
                    content: '支付失败，请稍后再试',
                    icon: 'delete'
                  });
                }
              }
            })
          } else if (res.data.code == 1005) {
            _this.setData({
              loading: false,
              disabled: false
            })
            $Toast({
              content: '订单重复提交',
              icon: 'delete'
            });
          } else {
            _this.setData({
              loading: false,
              disabled: false
            })
            $Toast({
              content: '支付失败，请稍后再试',
              icon: 'delete'
            });
          }
        }
      });
    } else {
      $Toast({
        content: '地址未选择',
        icon: 'delete'
      });
    }
  },

  /** 加载图片 */
  load_image(e) {
    /** 图片实际宽度和高度 */
    var imgW = e.detail.width;
    var imgH = e.detail.height;
    /** 图片宽度 */
    var imgWidth = this.data.imgWidth;
    var img_scale_hight = imgWidth / imgW * imgH; //计算图片应该显示的高度
    console.log(img_scale_hight)
    this.setData({
      img_height: img_scale_hight
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.showLoading({
      title: "数据加载中"
    });
    let sendData = {
      id: this.data.id,
      open_id: app.globalData.wxUserInfo.openId
    }
    wx.request({
      url: api.details.proDetail,
      data: sendData,
      header: {
        "content-type": "application/json"
      },
      method: 'GET',
      success(res) {
        console.log('产品详情数据', res.data.data)
        setTimeout(() => {
          wx.hideLoading()
          const content = res.data.data.proDesc || '';
          res.data.data.proDesc = that.formatRichText(content);
          that.setData({
            proData: res.data.data,
            isHavedCollect: res.data.data.product.isHavedCollect
          })
        }, 500)
      }
    })
  },
  formatRichText: function (html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
  },

  /** 收藏产品 */
  follow: function () {
    console.log('是否已收藏 -->', this.data.isHavedCollect)
    let that = this;
    if (!getApp().globalData.wxUserInfo.openId) {
      wx.showToast({
        title: '请登录',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.isHavedCollect == 0) {
      let sendData = {
        otherId: this.data.id,
        /** 收藏类型 2 表示产品 */
        type: 2,
        openId: getApp().globalData.wxUserInfo.openId,
        img: this.data.proData.product.img,
        title: this.data.proData.product.title
      }
      wx.request({
        url: api.follow.add_collect,
        data: sendData,
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          console.log('是否收藏数据返回 --> ', res)
          if (res.data.code == 200) {
            $Toast({
              content: '收藏成功',
              type: 'success'
            });
            that.setData({
              isHavedCollect: 1
            })
          }
        }
      });
    } else if (this.data.isHavedCollect == 1) {
      let sendData = {
        other_id: this.data.id,
        open_id: getApp().globalData.wxUserInfo.openId
      }
      wx.request({
        url: api.follow.del_collect,
        data: sendData,
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if (res.data.code == 200) {
            that.setData({
              isHavedCollect: 0
            })
            $Toast({
              content: '取消收藏',
              type: 'warning'
            });
          }
        }
      });
    }
  },
  /** 分享页面 */
  onShareAppMessage: function (type) {
    return {
      title: this.data.proData.product.title,
      path: `pages/productDetail/productDetail?id=${this.data.id}`,
      success: function (res) {},
      fail: function (res) {}
    }
  },

  /** 去添加地址 */
  addess() {
    let url = `/pages/productDetail/productDetail?id=${this.data.id}`
    /** 字符串编码 */
    let back_url = encodeURIComponent(url)
    console.log(back_url)
    /** 跳转到添加地址页面 */
    wx.reLaunch({
      url: `/pages/mine/address/add_address/add_address?back_url=${back_url}`,
    })
  },

  onReady: function () {
    const _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.getLocation({
                success(res) {
                  _this.getAddress(res.latitude, res.longitude)
                }
              })
            },
            /** 失败 */
            fail() {}
          })
        } else {
          // 已经授权了直接定位
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              _this.getAddress(res.latitude, res.longitude)
            }
          })
        }
      }
    })
  },
  /** 获取地理位置 */
  getAddress: function (latitude, longitude) {
    let that = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        that.setData({
          address: province + ' ' + city + ' ' + district,
        })
      }
    });
  },
});